﻿using System;
using System.Reactive.Linq;
using System.Windows;

namespace Wulong.Phone.Utils.ControlsHelper
{
    public static class ScrollViewerHelper
    {
        public static IObservable<System.Windows.Controls.ScrollViewer> GetObservableScrollViewer(object sender, DependencyPropertyListener listener)
        {
            return Observable.FromEventPattern<BindingChangedEventArgs>(
                h => listener.Changed += h,
                h => listener.Changed -= h)
                .Where(
                    n =>
                    {
                        if (n.Sender is FrameworkElement)
                        {
                            var frameElement = (FrameworkElement)sender;
                            var scrollViewer = CompUtils.FindChildOfType<System.Windows.Controls.ScrollViewer>(frameElement);
                            return scrollViewer != null && scrollViewer.VerticalOffset
                                   >= scrollViewer.ScrollableHeight;
                        }
                        return false;
                    }
                )
                .Select(n => n.Sender as System.Windows.Controls.ScrollViewer)
                .ObserveOnDispatcher()
                ;
        }
    }
}
